import { createStore } from 'vuex'
import axios from 'axios'

// 修改为后端实际运行的端口
const API_URL = 'http://localhost:8080/api'

// 配置axios默认设置
axios.defaults.timeout = 30000 // 30秒超时
axios.interceptors.request.use(request => {
  console.log('发送请求:', request.url, request.data)
  return request
})

export default createStore({
  state: {
    sessionId: localStorage.getItem('sessionId') || null,
    messages: [],
    loading: false,
    error: null,
    testCases: [],
    currentScreenshot: null,
    currentStreamContent: '',  // 添加这行
    chatSessions: [], // 添加会话列表
  },
  getters: {
    getMessages: state => state.messages,
    isLoading: state => state.loading,
    getError: state => state.error,
    getSessionId: state => state.sessionId,
    getTestCases: state => state.testCases,
    getCurrentScreenshot: state => state.currentScreenshot
  },
  mutations: {
    SET_SESSION_ID(state, sessionId) {
      state.sessionId = sessionId
      localStorage.setItem('sessionId', sessionId)
    },
    SET_MESSAGES(state, messages) {
      state.messages = messages
    },
    ADD_MESSAGE(state, message) {
      state.messages.push(message)
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    },
    SET_TEST_CASES(state, testCases) {
      state.testCases = testCases
    },
    ADD_TEST_CASE(state, testCase) {
      state.testCases.push(testCase)
    },
    SET_CURRENT_SCREENSHOT(state, path) {
      state.currentScreenshot = path
    },
    UPDATE_STREAM_CONTENT(state, content) {
      state.currentStreamContent = content
    },
    SET_CHAT_SESSIONS(state, sessions) {
      state.chatSessions = sessions
    },
    ADD_CHAT_SESSION(state, session) {
      state.chatSessions.unshift(session)
    },
    UPDATE_SESSION(state, { sessionId, updates }) {
      const index = state.chatSessions.findIndex(s => s.sessionId === sessionId)
      if (index !== -1) {
        state.chatSessions[index] = { ...state.chatSessions[index], ...updates }
      }
    },
    REMOVE_CHAT_SESSION(state, sessionId) {
      state.chatSessions = state.chatSessions.filter(
        session => session.sessionId !== sessionId
      )
    }
  },
  actions: {
    async sendMessage({ commit, state }, content) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      commit('UPDATE_STREAM_CONTENT', '')
      
      try {
        const userMessage = {
          role: 'user',
          content,
          timestamp: new Date().toISOString()
        }
        commit('ADD_MESSAGE', userMessage)
        
        // Modified axios request configuration
        const response = await axios.post(`${API_URL}/chat/send`, {
          sessionId: state.sessionId,
          content
        }, {
          onDownloadProgress: (progressEvent) => {
            const text = progressEvent.target?.response || ''
            try {
              // Handle streaming response
              if (text) {
                commit('UPDATE_STREAM_CONTENT', text)
              }
            } catch (e) {
              console.error('Error processing stream:', e)
            }
          }
        })
        
        // Handle final response
        if (response.data?.message) {
          commit('ADD_MESSAGE', response.data.message)
          commit('UPDATE_STREAM_CONTENT', '')
        }
        
        return response.data?.message
        
      } catch (error) {
        console.error('发送消息失败:', error)
        
        // 更详细的错误处理
        if (error.response?.status === 500) {
          console.error('服务器内部错误详情:', error.response.data)
          
          // 尝试提取更具体的错误信息
          let errorDetail = '未知错误';
          try {
            if (typeof error.response.data === 'string') {
              errorDetail = error.response.data;
            } else if (error.response.data.message) {
              errorDetail = error.response.data.message;
            } else if (error.response.data.error) {
              errorDetail = error.response.data.error;
            }
          } catch (e) {
            console.error('解析错误详情失败:', e);
          }
          
          commit('SET_ERROR', `服务器内部错误: ${errorDetail}`)
          
          const errorMessage = {
            role: 'system',
            content: `⚠️ 服务器发生错误: ${errorDetail}\n\n可能的原因：\n1. API密钥无效\n2. 后端端口配置错误(当前: ${API_URL})\n3. 网络连接问题\n4. 后端代码异常`,
            timestamp: new Date().toISOString()
          }
          commit('ADD_MESSAGE', errorMessage)
        } else {
          console.error('错误详情:', error.response?.data || error.message)
          console.error('错误状态码:', error.response?.status)
          console.error('请求配置:', error.config)
          commit('SET_ERROR', error.response?.data?.error || error.message)
        }
        
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },  
    
    async loadChatSessions({ commit }) {
      try {
        const response = await axios.get(`${API_URL}/chat/sessions`)
        commit('SET_CHAT_SESSIONS', response.data)
      } catch (error) {
        console.error('加载会话列表失败:', error)
      }
    },  
    
    async createNewSession({ commit }) {
      try {
        const response = await axios.post(`${API_URL}/chat/sessions`)
        const newSession = response.data
        commit('SET_SESSION_ID', newSession.sessionId)
        commit('ADD_CHAT_SESSION', newSession)
        commit('SET_MESSAGES', [])
      } catch (error) {
        console.error('创建新会话失败:', error)
      }
    }, 
    
    async switchSession({ commit }, sessionId) {
      try {
        commit('SET_SESSION_ID', sessionId)
        const response = await axios.get(`${API_URL}/chat/history/${sessionId}`)
        commit('SET_MESSAGES', response.data)
      } catch (error) {
        console.error('切换会话失败:', error)
      }
    },
    
    async captureScreen({ commit }) {
      try {
        const response = await axios.post(`${API_URL}/testcase/capture`)
        commit('SET_CURRENT_SCREENSHOT', response.data.screenshotPath)
        return response.data.screenshotPath
      } catch (error) {
        console.error('截图失败:', error)
        throw error
      }
    },
    
    async createTestCase({ commit }, testCase) {
      try {
        // 确保数据完整性，并处理大文本内容
        const testCaseData = {
          ...testCase,
          content: testCase.content || '',
          uiStructure: testCase.uiStructure || '',
          createdAt: new Date().toISOString()
        }
        
        const response = await axios.post(`${API_URL}/testcase`, testCaseData, {
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          // 增加超时时间和最大内容大小限制
          timeout: 60000, // 60秒
          maxContentLength: Infinity,
          maxBodyLength: Infinity
        })
        
        if (response.data) {
          // 确保大文本内容正确保存
          const savedTestCase = {
            ...response.data,
            content: response.data.content || '',
            uiStructure: response.data.uiStructure || ''
          }
          commit('ADD_TEST_CASE', savedTestCase)
          return savedTestCase
        } else {
          throw new Error('创建测试用例失败：服务器返回空数据')
        }
      } catch (error) {
        console.error('创建测试用例失败:', error)
        throw error
      }
    },
    
    async loadTestCases({ commit }) {
      try {
        const response = await axios.get(`${API_URL}/testcase`, {
          // 增加超时时间，因为可能需要加载大量数据
          timeout: 30000,
          maxContentLength: Infinity
        })
        
        // 确保所有测试用例的大文本字段都有默认值
        const processedTestCases = response.data.map(testCase => ({
          ...testCase,
          content: testCase.content || '',
          uiStructure: testCase.uiStructure || ''
        }))
        
        commit('SET_TEST_CASES', processedTestCases)
      } catch (error) {
        console.error('加载测试用例失败:', error)
      }
    },
    async deleteSession({ commit, state }, sessionId) {  // 添加 state 到解构参数中
      try {
        await axios.delete(`${API_URL}/chat/sessions/${sessionId}`)
        commit('REMOVE_CHAT_SESSION', sessionId)
        if (sessionId === state.sessionId) {
          commit('SET_SESSION_ID', null)
          commit('SET_MESSAGES', [])
        }
      } catch (error) {
        console.error('删除会话失败:', error)
        throw error
      }
    }
  }
})